package com.google.code.bankagregator.core;

import com.google.code.bankagregator.adapter.Adapter;
import com.google.code.bankagregator.vo.AdapterResult;
import org.reflections.Reflections;

import javax.ejb.Stateless;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Class for collecting credits and deposits from each of bankName adapters
 */

@Stateless
public class AdapterManager {

    /**
     * Collect List<AdapterResult> from Adapters.
     *
     * @return
     */
    public List<AdapterResult> getAllResults() {
        List<AdapterResult> results = new ArrayList<AdapterResult>();
        Set<Class<? extends Adapter>> adapters = getAdapterList();
        for (Class classInstance : adapters) {
            try {
                Adapter adapter = (Adapter) classInstance.newInstance();
                AdapterResult adapterResult = adapter.getResult();
                results.add(adapterResult);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return results;
    }

    /**
     * Getting set of bank Adapters
     *
     * @return Set
     */
    private Set<Class<? extends Adapter>> getAdapterList() {
        Reflections reflections = new Reflections("com.google.code.bankagregator.adapter");
        Set<Class<? extends Adapter>> adapters = reflections.getSubTypesOf(Adapter.class);
        return adapters;
    }
}
